package org.hong.monkey.metrics.sink

import java.util.Properties
import java.util.concurrent.TimeUnit
import javax.servlet.http.HttpServletRequest

import com.codahale.metrics.MetricRegistry
import com.codahale.metrics.json.MetricsModule
import com.fasterxml.jackson.databind.ObjectMapper
import org.eclipse.jetty.servlet.ServletContextHandler
import org.hong.monkey.MonkeyConf
import org.hong.monkey.ui.JettyUtils._

private[monkey] class MetricsServlet (
  val property: Properties,
  val registry: MetricRegistry
  ) extends Sink {

  val SERVLET_KEY_PATH = "path"

  val SERVLET_KEY_SAMPLE = "sample"

  val SERVLET_DEFAULT_SAMPLE = false

  val servletPath = property.getProperty(SERVLET_KEY_PATH)

  val servletShowSample = Option(property.getProperty(SERVLET_KEY_SAMPLE)).map(_.toBoolean)
    .getOrElse(SERVLET_DEFAULT_SAMPLE)

  val module = new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, servletShowSample)
  val mapper = new ObjectMapper().registerModule(module)

  def getHandlers(conf: MonkeyConf): Array[ServletContextHandler] = {
    Array[ServletContextHandler](
     createServletHandler(servletPath,
     new ServletParams(request => getMetricsSnapshot(request), "text/json"), conf)
    )
    Array.empty[ServletContextHandler]
  }

  def getMetricsSnapshot(request: HttpServletRequest): String = {
    mapper.writeValueAsString(registry)
  }

  override def start(): Unit = {}

  override def stop(): Unit = {}

  override def report(): Unit = {}
}
